package month1;

public class LowestCommonAncestor236_05 {
    public static void main(String[] args) {
        TreeNode treeNode = new TreeNode(new Integer[]{3, 5, 1, 6, 2, 0, 8, null, null, 7, 4});
        TreeNode p = treeNode.left, q = treeNode.right;
        System.out.println(lowestCommonAncestor(treeNode, p, q));
    }

    /**
     * 递归吧
     * @param root
     * @param p
     * @param q
     * @return 这里返回的寓意是在左右子树上是否能找到节点
     */
    static TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        if (root == null || root == p || root == q) {
            return root;
        }
        TreeNode left = lowestCommonAncestor(root.left, p, q), right = lowestCommonAncestor(root.right, p, q);
        if (left != null && right != null) {
            return root;
        } else if (left != null) {
            return left;
        } else if (right != null) {
            return right;
        }
        return null;
    }
}
